package org.wat.wcy.isi.mmazur.bp.conf;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class Config {

	private static final String NODE_FILE_NAME = "nodes.dat";
	private static final String MATIX_FILE_NAME = "matrix.dat";
	private static final String CONFIG_FILE = "config.xml";

	private String dataDir;

	private static Config instance;

	private Config() {
		loadConfig();
	}

	private void loadConfig() {
		String userDir = System.getProperty("user.home");
		File file = new File(userDir, CONFIG_FILE);
		try {

			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
			Document doc = docBuilder.parse(file);

			XPathFactory factory = XPathFactory.newInstance();
			XPath xpath = factory.newXPath();
			javax.xml.xpath.XPathExpression expr = xpath
					.compile("/config/store-path[1]");
			Object result = expr.evaluate(doc, XPathConstants.NODESET);
			NodeList nodes = (NodeList) result;
			dataDir = nodes.item(0).getTextContent();
		} catch (SAXParseException err) {
			err.printStackTrace();
		} catch (SAXException e) {
			Exception x = e.getException();
			((x == null) ? e : x).printStackTrace();

		} catch (Throwable t) {
			t.printStackTrace();
		}
	}

	synchronized public static Config getInstance() {
		if (instance == null) {
			instance = new Config();
		}
		return instance;
	}

	public String getDataDir() {
		return dataDir;
	}

	public String resolveNodeFile(String processName) {
		return resolveFileName(processName, NODE_FILE_NAME);
	}

	public String resolveMatrixFile(String processName) {
		return resolveFileName(processName, MATIX_FILE_NAME);
	}

	private String resolveFileName(String processName, String nodeFileName) {
		StringBuilder strb = new StringBuilder();
		strb.append(dataDir);
		strb.append(File.separatorChar);
		strb.append(processName);
		strb.append(File.separatorChar);
		strb.append(nodeFileName);
		return strb.toString();
	}

	public String getProjectDir(String processId) {
		return getDataDir() + File.separator + processId;
	}
}